import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import { updateProductAction } from '../../store/actionCreator'
import styles from './NewItemList.module.scss'
import axios from 'axios'
class NewItemList extends Component {
  state = {
    newItemList: [],
    lovingList: [],
  }
  isLoading = false
  list = []
  componentDidMount() {
    this.list = [...this.props.list]
    this.loadMore()
    /* 监听滚动 */
    window.addEventListener('scroll', () => {
      this.scrollHandler()
    })
    /* 强制刷新 */
    window.addEventListener('popstate', () => {
      window.location.reload()
    })
    /* 请求猜你喜欢数据 */
    var productInfo= JSON.parse(window.localStorage.getItem('productInfo'))||{}
    var id=productInfo.itemId||this.props.id
    var formData = new FormData()
    formData.append('id', id)
    axios({
      url: '/xhr/wapitem/rcmd.json',
      method: 'post',
      headers: { 'X-Requested-With': 'XMLHttpRequest' },
      data: formData,
    }).then((res) => {
      let list =res.data.data.items
      this.setState({
        lovingList:[list.slice(0, 2),
          list.slice(2, 4),
          list.slice(4, 6),
          list.slice(6, 8),
          list.slice(8, 10),]
      },)
    })
  /* 请求猜你喜欢数据结束 */ 
  }
  scrollHandler() {
    if (this.isLoading) return
    if (!this.refs.con) return
    let h =
      this.refs.con.clientHeight -
      document.documentElement.scrollTop -
      document.documentElement.clientHeight
    if (h <= 0) {
      this.loadMore()
    }
  }
  loadMore() {
    this.isLoading = true
    let list=[]
    if(this.list.length>=10){
      list = this.list.splice(0, 10)
    }else{
      list = this.list
    }
    let newItemList=[]
    for (let i=0;i<Math.ceil(list.length/2);i++){
      if (list.length){
        newItemList.push(list.splice(0,2))
      }
    }
    this.setState(
      {
        newItemList:[...this.state.newItemList,...newItemList]
      },
      () => {
        this.isLoading = false
      }
    )
    /* 加载完成就停止不再加载 */
    if(!this.list.length){
      this.isLoading=true
    }
  }
  render() {
    return (
      <div className={styles.newItemListCon} ref="con">
        {/* 搜索结果列表开始 */}
        <div className={styles.newItemListTit}>
          <div className={styles.newItemListTitLt}>
            搜索到{this.props.list.length}件商品
          </div>
          <div
            className={styles.newItemListTitMore}
            onClick={() => {
              this.loadMore()
            }}
          >
            更多{' '}
          </div>
        </div>
        {this.state.newItemList &&
          this.state.newItemList.map((item, i) => (
            <div className={styles.NewItemList} key={i}>
              {item.map((v) => (
                <div
                  className={styles.NewItemListItem}
                  key={v.displaySkuId}
                  onClick={() => {
                    this.props.history.push('/ProductDetail/?id=' + v.id)
                  }}
                >
                  <img src={v.primaryPicUrl} alt="" />
                  <div className={styles.newItemTitle}>{v.name}</div>
                  <div className={styles.newItemPrice}>¥{v.retailPrice}</div>
                  <div className={styles.newItemTag}>
                    {v.itemTagList &&
                      v.itemTagList.map((val) => (
                        <span key={val.tagId + '-' + v.itemId}>{val.name}</span>
                      ))}
                  </div>
                </div>
              ))}
            </div>
          ))}
        {/* 列表加载完成 */}
        {/* 猜你喜欢开始 */}
        {
         
        !this.state.newItemList.length&&<div>
           {/* 猜你喜欢开始 */}
           <div className="lovingGoodTit">
            <div className="itemLine"></div>
            <span className="itemText">你可能还喜欢</span>
          </div>
          {
            this.state.lovingList.map((item, i) => (
              <div className="NewItemList" key={i}>
                {item.map((v, i) => (
                  <div
                    className="NewItemListItem"
                    key={v.displaySkuId}
                    onClick={() => {
                      this.props.history.push('/ProductDetail/?id=' + v.id)
                    }}
                  >
                    <img src={v.primaryPicUrl} alt="" />
                    <div className="newItemTitle">{v.name}</div>
                    <div className="newItemPrice">¥{v.retailPrice}</div>
                    <div className="newItemTag">
                      {v.itemTagList &&
                        v.itemTagList.map((val, i) => (
                          <span key={val.name + val.tagId}>{val.name}</span>
                        ))}
                    </div>
                  </div>
                ))}
              </div>
            ))}
        {/* 猜你喜欢结束 */}
        </div>
        }
        {/* 猜你喜欢结束 */}
      </div>
    )
  }
}
const mapStateToProps = (state) => {
  return {
    productReducer: state.getIn(['productReducer']),
    id: state.getIn(['productReducer','productInfo','itemId'])
  }
}
const mapDispatchToProps = (dispatch) => {
  return {
    updateProduct: (detail) => {
      dispatch(updateProductAction(detail))
    },
  }
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(NewItemList))
